<style lang="scss" type="text/scss">
  .chart-con {
    flex: 1 1 auto;
    display: flex;
    position: relative;
    flex-direction: column;
    .chart-box {
      flex: 1 1 auto;
      background: #fff;
      overflow-x: auto;
      padding-bottom: 20px;
      > div.echart-con {
        display: flex;
        /*border-bottom: 1px solid #e5e5e5;*/
        /*padding-bottom: 20px;*/
      }
      .box {
        width: 400px;
        height: 400px;
      }
    }
    .chart-title {
      height: 40px;
      line-height: 40px;
      position: relative;
      padding: 0 30px;
      border-bottom: 1px solid #e5e5e5;
      a.edit-btn {
        position: absolute;
        font-size: 14px;
        top: 0;
        right: 30px;
        z-index: 1;
      }
    }
    .type-panel {
      display: flex;
      flex-direction: row;
      position: fixed;
      right: 0;
      top: 0;
      z-index: 10;
      a {
        display: inline-block;
        background-color: #4d4d4d;
        width: 36px;
        height: 36px;
        margin-right: 5px;
        &:hover,
        &.active {
          background-color: #1199d9;
        }
        img {
          width: 100%;
        }
      }
    }
  }
</style>

<template>
  <div>
    <div v-if="loaded" class="chart-con">
      <div class="type-panel" @click="chartClick($event)">
        <el-dropdown v-for="item in chartSmart" :key="item.id" @command="handleCommand">
          <a :class="{active:chartType === item.type}" href="javascript:">
            <img :type="item.type" :src="'static/images/'+item.type+'_icon.png'"/></a>
          <el-dropdown-menu :type="item.type" slot="dropdown">
            <el-dropdown-item v-for="sub in item.list" :key="sub.id" :command="sub.type">{{sub.name}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="chart-title"
           :style="'text-align:'+form.title.left+';font-size:'+form.title.textStyle.fontSize+'px;color:'+form.title.textStyle.color">
        <span v-show="this.form.title.parShow === 1">{{form.title.text}}</span>
        <el-tooltip class="item" effect="dark" content="设置" placement="right">
          <a class="edit-btn" href="javascript:" @click="showRight=true"><i class="el-icon-setting"></i></a>
        </el-tooltip>
      </div>
      <echart-bar class="chart-box" ref="tchart" v-if="chartType == 'bar' && loaded" :form="form"></echart-bar>
      <echart-pie class="chart-box" ref="tchart" v-else-if="chartType == 'pie' && loaded" :form="form"></echart-pie>
      <echart-line class="chart-box" ref="tchart" v-else-if="chartType == 'line' && loaded" :form="form"></echart-line>
      <echart-radar class="chart-box" ref="tchart" v-else-if="chartType == 'radar' && loaded"
                    :form="form"></echart-radar>
      <echart-treemap class="chart-box" ref="tchart" v-else-if="chartType == 'treemap' && loaded"
                      :form="form"></echart-treemap>
    </div>
    <page-right :show="showRight" @right-close="resetRightBox">
      <el-radio-group v-model="chartType" style="margin-bottom: 30px;">
        <el-radio-button v-for="item in chartSmart" :label="item.type" :key="item.id">{{item.name}}</el-radio-button>
      </el-radio-group>
      <el-tabs>
        <el-tab-pane label="基本设置">
          <el-form ref="form" :model="form" size="mini">
            <!--<el-form-item label="画布大小">
              <el-row type="flex">
                <el-col :span="6">
                  <el-input placeholder="请输入宽" v-model.lazy="form.content.width">
                    <template slot="prepend">宽</template>
                  </el-input>
                </el-col>
                <el-col :span="6" :offset="1">
                  <el-input placeholder="请输入高" v-model.lazy="form.content.height">
                    <template slot="prepend">高</template>
                  </el-input>
                </el-col>
                <el-col :span="6" :offset="1">
                  <el-button @click="resetSize" size="mini">重置</el-button>
                </el-col>
              </el-row>
            </el-form-item>-->
            <el-form-item label="背影颜色">
              <el-color-picker v-model="form.backgroundColor"></el-color-picker>
            </el-form-item>
            <el-form-item label="初始动画">
              <el-tooltip content="是否显示初始动画" placement="top">
                <el-switch v-model="form.animation" :active-value="1" :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="坐标切换">
              <el-tooltip content="是否切换坐标" placement="top">
                <el-switch v-model="form.barre" :active-value="1" :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </el-form-item>
            <el-form-item v-if="chartType == 'line'" label="是否平滑">
              <el-tooltip content="是否平滑展示" placement="top">
                <el-switch v-model="form.line.smooth" :active-value="1" :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </el-form-item>

            <el-form-item v-if="chartType == 'line'" label="阶梯类型">
              <el-radio-group v-model.lazy="form.line.step">
                <el-radio-button label="start">开始</el-radio-button>
                <el-radio-button label="middle">中间</el-radio-button>
                <el-radio-button label="end">结束</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="图例显示">
              <el-tooltip content="是否显示图例" placement="top">
                <el-switch v-model="form.legend.show" :active-value="1" :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="图例类型">
              <el-radio-group v-model.lazy="form.legend.type">
                <el-radio-button label="plain">普通图例</el-radio-button>
                <el-radio-button label="scroll">滚动翻页</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="图例位置">
              <el-radio-group v-model.lazy="form.legend.location">
                <el-radio-button label="0">左上</el-radio-button>
                <el-radio-button label="1">中上</el-radio-button>
                <el-radio-button label="2">右上</el-radio-button>
                <el-radio-button label="3">左中</el-radio-button>
                <el-radio-button label="4">右中</el-radio-button>
                <el-radio-button label="5">左下</el-radio-button>
                <el-radio-button label="6">中下</el-radio-button>
                <el-radio-button label="7">右下</el-radio-button>
              </el-radio-group>

            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="标题">
          <el-form ref="form" :model="form" size="mini">
            <el-form-item label="标题显隐">
              <el-tooltip content="是否显示标题" placement="top">
                <el-switch v-model="form.title.parShow" :active-value="1" :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="标题名字">
              <el-row>
                <el-col :span="10">
                  <el-input placeholder="请输入标题" v-model="form.title.text"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="标题样式">
              <el-row>
                <el-col :span="6">
                  <el-select v-model="form.title.textStyle.fontSize" placeholder="字体大小">
                    <el-option label="18" value="18"></el-option>
                    <el-option label="20" value="20"></el-option>
                    <el-option label="25" value="25"></el-option>
                    <el-option label="30" value="30"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="6" :offset="1">
                  <el-color-picker v-model="form.title.textStyle.color"></el-color-picker>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="水平位置">
              <el-radio-group v-model.lazy="form.title.left">
                <el-radio-button label="left">居左</el-radio-button>
                <el-radio-button label="center">居中</el-radio-button>
                <el-radio-button label="right">居右</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="坐标轴">
          <el-form ref="form" :model="form" size="mini">
            <el-form-item label="分类X轴名称">
              <el-input placeholder="分类X轴名称" v-model="form.xAxis.name"></el-input>
            </el-form-item>
            <el-form-item label="指标Y轴名称">
              <el-input placeholder="指标Y轴名称" v-model="form.yAxis.name"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="提示">
          <el-form ref="form" :model="form" size="mini">
            <el-form-item label="是否显示">
              <el-tooltip content="是否显示提示框组件" placement="top">
                <el-switch v-model="form.tooltip.show" :active-value="1" :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="类型">
          <el-form ref="form" :model="form" size="mini">
            <el-form-item v-for="item in chartSmart" :key="item.id" v-if="chartType == item.type">
              <el-radio-group v-model.lazy="form.echart[item.type]">
                <el-radio-button v-for="list in item.list" :key="list.id" :label="list.type">{{list.name}}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </page-right>
  </div>
</template>

<script>
  import 'echarts';
  import {http, chart} from '@/resources';
  import echartBar from '@/components/echarts/echart.bar.vue';
  import echartPie from '@/components/echarts/echart.pie.vue';
  import echartLine from '@/components/echarts/echart.line.vue';
  import echartRadar from '@/components/echarts/echart.radar.vue';
  import echartTreemap from '@/components/echarts/echart.treemap.vue';
  import utils from '@/tools/utils';

  let smart = [
    {
      type: 'bar',
      name: '柱状图',
      list: [
        {
          type: 'default',
          name: '标准柱图'
        },
        {
          type: 'stack',
          name: '堆积柱图'
        }
      ]
    },
    {
      type: 'pie',
      name: '饼图',
      list: [
        {
          type: 'default',
          name: '标准饼图'
        },
        {
          type: 'annular',
          name: '环形图'
        },
        {
          type: 'radius',
          name: '南丁格尔图A'
        },
        {
          type: 'area',
          name: '南丁格尔图B'
        }
      ]
    },
    {
      type: 'line',
      name: '线图',
      list: [
        {
          type: 'default',
          name: '标准线图'
        },
        {
          type: 'area',
          name: '面积图'
        },
        {
          type: 'stack',
          name: '堆积线图'
        },
        {
          type: 'areaStack',
          name: '堆积面积图'
        },
        {
          type: 'step',
          name: '阶梯线图'
        }
      ]
    },
    {
      type: 'radar',
      name: '雷达图',
      list: []
    },
    {
      type: 'treemap',
      name: '树映射',
      list: []
    }
  ];

  export default {
    data: function () {
      let that = this;
      let timer = '';
      return {
        thumbImg: '',
        loaded: false,
        chartId: this.$route.params.chartId,
        chartType: 'bar',
        chartSmart: smart,
        showRight: false,
        chartTag: {
          xAxis: [],
          yAxis: [],
          color: [],
          size: [],
          detail: [],
          tag: [],
          tip: [],
          filters: []
        },
        form: {
          series: [],
          originalData: {},
          content: {
            width: '',
            height: '',
            boxWidth: ''
          },
          plot: {
            tags: [],
            value: [],
            category: []
          },
          title: {
            parShow: 1,
            show: false,
            text: '',
            textStyle: {
              color: '#333',
              fontSize: '18'
            },
            left: 'left'
          },
          barre: 0,
          legend: {
            show: 1,
            location: '6',
            type: 'plain'
          },
          backgroundColor: '#fff',
          animation: 1,
          tooltip: {
            show: 1,
            formatter: function (params, ticket, callback) {
              return that.getFormatterStr(params);
            }
          },
          xAxis: {
            name: '',
            type: 'category'
          },
          yAxis: {
            name: '',
            type: 'value'
          },
          line: {
            smooth: 0,
            step: 'middle'
          },
          echart: {
            bar: 'default',
            pie: 'default',
            line: 'default'
          }
        },
        saveTimer: ''
      };
    },
    computed: {
      isChange: function () {
        return this.$store.state.chartOptChange;
      },
      rightWidth() {
        let width = this.$store.state.bodyWidth - 520;
        return width;
      },
      rightHeight() {
        let height = this.$store.state.bodyHeight - 190;
        return height;
      },
      boxWidth() {
        let boxWidth = '';
        let width = this.$store.state.bodyWidth - 520;
        if (this.chartType === 'bar' || this.chartType === 'line') {
          if (this.form.plot.value.length <= 1) {
            boxWidth = width - 10;
          } else {
            boxWidth = Math.floor(width / 300) > 3 ? 360 : Math.floor(width / 3) + 120;
          }
        } else if (this.chartType === 'pie') {
          if (this.form.plot.category.length <= 1) {
            boxWidth = width - 10;
          } else {
            boxWidth = Math.floor(width / 300) > 3 ? 360 : Math.floor(width / 3) + 120;
          }
        } else if (this.chartType === 'radar') {
          if (this.form.plot.category.length <= 1) {
            boxWidth = width - 10;
          } else {
            boxWidth = Math.floor(width / 300) > 3 ? 360 : Math.floor(width / 3) + 120;
          }
        }
        return boxWidth;
      }
    },
    components: {
      echartBar,
      echartPie,
      echartLine,
      echartRadar,
      echartTreemap
    },
    watch: {
      form: {
        handler(form) {
          this.saveChartOpt();
        },
        deep: true
      },
      rightHeight: function (val) {
        this.form.content.height = val;
      },
      rightWidth: function (val) {
        this.form.content.width = val;
      },
      boxWidth: function (val) {
        this.form.content.boxWidth = val;
      },
      isChange: function (val) {
        if (val) {
          this.getChartData();
          this.$store.commit('chartOptionChange', false);
        }
      },
      chartType: function () {
        chart.update(this.chartId, {type: this.chartType}).then(res => {
          this.initChart();
        });
      }
    },
    methods: {
      getChartInit() {
        chart.get(this.chartId).then(res => {
          if (!res.data) {
            return false;
          }
          if (res.data.opt) {
            if (utils.isString(res.data.opt)) {
              res.data.opt = JSON.parse(res.data.opt);
            }
            this.form = Object.assign({}, this.form, res.data.opt);
          }
          if (res.data.tag) {
            if (utils.isString(res.data.tag)) {
              res.data.tag = JSON.parse(res.data.tag);
            }

            this.chartTag = Object.assign({}, this.chartTag, res.data.tag);
          }
          if (res.data.type) {
            this.chartType = res.data.type;
          }
          this.form.title.text = res.data.title;
          this.form.title.show = false;
          this.initChart();
        });
      },
      getChartData: function () {
        clearTimeout(this.saveTimer);
        this.saveTimer = setTimeout(() => {
          let tagStr = sessionStorage.getItem('charts_' + this.chartId + '_chartTag');
          if (!tagStr) {
            return false;
          }
          this.chartTag = JSON.parse(tagStr);
          if (this.loaded) {
            chart.update(this.chartId, {tag: tagStr}).then(res => {});
          }
          let xAxisData = {dimension: [], measure: [], fiters: []};
          let currentKeyArr = [];
          for (let key of Object.keys(this.chartTag)) {
            if (key === 'filters') {
              xAxisData.fiters = this.chartTag.filters;
            } else {
              this.chartTag[key].forEach(item => {
                if (currentKeyArr.indexOf(item.name) === -1) {
                  currentKeyArr.push(item.name);
                  if (item.type === 'value') {
                    xAxisData.measure.push(item.name);
                  } else {
                    xAxisData.dimension.push(item.name);
                  }

                }
              });
            }
          }
          if (xAxisData.dimension.length === 0 || xAxisData.measure.length === 0) {
            this.form.originalData = '';
            this.initChart();
            return false;
          }
          http.post('data/' + this.chartId, xAxisData).then(res => {
            if (res.data && res.data.data) {
              this.form.originalData = res.data.data;
              this.initChart();
            }
          });
        }, 100);
      },
      saveChartOpt(options) {
        clearTimeout(this.saveTimer);
        this.saveTimer = setTimeout(() => {
          let tempForm = {};
          for (let i in this.form) {
            if (i !== 'tooltip') {
              tempForm[i] = this.form[i];
            }
          }
          let chartV_ref = this.$refs.tchart;
          let url = '';
          if (chartV_ref) {
            let chart_ref = chartV_ref.$refs.chart;
            if (Array.isArray(chart_ref)) {
              chart_ref.forEach(item => {
                item.resize();
              });
              if (chart_ref[0]) {
                url = chart_ref[0].getDataURL();
              }
            }
            if (this.loaded) {
              let dataArr = {};
              dataArr.opt = JSON.stringify(tempForm);
              if (url) {
                dataArr.image = url;
              }
              chart.update(this.chartId, dataArr);
            }
          }
        }, 150);
      },
      initChart() {
        if (!this.form.originalData || this.form.originalData.length === 0) {
          return;
        }
        this.form.content.width = this.rightWidth;
        this.form.content.height = this.rightHeight;
        this.form.content.boxWidth = this.boxWidth;
        this.form.plot.category = [];
        this.form.plot.value = [];
        this.chartTag.xAxis.forEach(item => {
          if (item.type === 'category') {
            this.form.plot.category.push(item);
          } else {
            this.form.plot.value.push(item);
          }
        });
        this.chartTag.yAxis.forEach(item => {
          if (item.type === 'category') {
            this.form.plot.category.push(item);
          } else {
            this.form.plot.value.push(item);
          }
        });
        this.form.plot.tags = [];
        this.chartTag.tag.forEach(item => {
          this.form.plot.tags.push(item.name);
        });
        this.loaded = true;
      },
      chartClick(event) {
        let e = event.target;
        if (e.tagName.toLowerCase() === 'img') {
          this.chartType = e.getAttribute('type');
        }
      },
      handleCommand(command, item) {
        let type = item.$parent.$el.getAttribute('type');
        this.chartType = type;
        this.form.echart[type] = command;
      },
      resetSize() {
        this.form.content.width = this.rightWidth;
        this.form.content.height = this.rightHeight;
      },
      resetRightBox() {
        this.showRight = false;
      },
      getSeriesTitle(name) {
        let title = '';
        if (this.form.series.length === 0) {
          let seriesStr = sessionStorage.getItem(
            'ds_' + this.chartId + '_series'
          );
          if (!seriesStr) {
            return '';
          }
          this.form.series = JSON.parse(seriesStr);
        }
        this.form.series.forEach(item => {
          if (item.name === name) {
            title = item.title;
          }
        });
        return title;
      },
      getFormatterStr(paras) {
        let showArr = [];
        if (this.form.plot.category.length > 0) {
          this.form.plot.category.forEach(item => {
            showArr.push({
              name: item.name,
              title: this.getSeriesTitle(item.name)
            });
          });
        }
        if (this.form.plot.value.length > 0) {
          this.form.plot.value.forEach(item => {
            showArr.push({
              name: item.name,
              title: this.getSeriesTitle(item.name)
            });
          });
        }

        this.chartTag.tip.forEach(item => {
          showArr.push({name: item.name, title: item.title});
        });
        this.chartTag.detail.forEach(item => {
          showArr.push({name: item.name, title: item.title});
        });
        let reStr = '';
        let reSeriesName = paras.seriesName;
        let reName = paras.name;
        if (this.chartType === 'pie' && this.form.plot.category[1]) {
          reSeriesName = paras.name;
          reName = paras.seriesName;
        }
        this.form.originalData.forEach(list => {
          let showUnionArr = [];
          let isUnion = true;
          showArr.forEach(item => {
            isUnion = true;
            showUnionArr.forEach(arr => {
              if (arr.name === item.name) {
                isUnion = false;
              }
            });
            if (isUnion) {
              showUnionArr.push(item);
              if (this.form.plot.category[0] &&
                list[this.form.plot.category[0].name] === reName &&
                this.form.plot.category[1] &&
                list[this.form.plot.category[1].name] === reSeriesName
              ) {
                reStr += '<div>' + item.title + ':' + list[item.name] + '</div>';
              } else if (
                this.form.plot.category[0] &&
                list[this.form.plot.category[0].name] === reName &&
                !this.form.plot.category[1]
              ) {
                reStr += '<div>' + item.title + ':' + list[item.name] + '</div>';
              }
            }
          });
        });
        return reStr;
      }
    },
    mounted() {
      this.getChartInit();
    }
  };
</script>
